import re
import logging

from django.shortcuts import render
from django.views import View

from portal.visitor_list.models import VisitorModel
from .constants import DontNeedLogPath, DontNeedLogIP

# Create your views here.

visitor_logger = logging.getLogger("visitor")


def ip_filter(ip_string):
    """判断 IP 是否要被记录"""

    for match in DontNeedLogIP:
        if re.findall(match, ip_string):
            return False
    return True


class HomePageView(View):
    """首页视图"""

    def get(self, request):
        user_agent_parse = {
            "device": request.USER_AGENT_PARSE["device"],
            "browser": request.USER_AGENT_PARSE["browser"],
            "system": request.USER_AGENT_PARSE["system"],
            "ip": request.USER_AGENT_PARSE["ip"],
            "user_agent": request.USER_AGENT_PARSE["user_agent"]
        }

        ip = request.META["REMOTE_ADDR"]

        if not ip_filter(ip) or request.is_ajax() or request.path_info in DontNeedLogPath:  # 内网访问的 IP 不记录数据库
            pass
        else:
            try:
                VisitorModel.objects.create(**user_agent_parse)  # 入库
            except Exception as e:
                visitor_logger.error(e)

        context = {}
        context.update(request.USER_AGENT_PARSE)
        return render(self.request, "home.html", context=context)
